﻿using Furion.FriendlyException;

namespace Utils;


public class PhoneCode
{

    /// <summary>
    /// 发送验证码
    /// </summary>
    /// <param name="phone"></param>
    /// <returns></returns>
    public static async Task Send(string phone)
    {
        string ExisKey = $"PHONECODE_EXIS_{phone}";

        string CodeKey = $"PHONECODE_CODE_{phone}";

        if (await RedisHelper.ExistsAsync(ExisKey)) throw Oops.Oh("请一分钟后发送");

        string Code = new Random().Next(000000, 999999).ToString();

        bool state = await Sms.PhoneCode(phone,Code);

        if (!state) throw Oops.Oh("发送失败");
      
        await RedisHelper.SetAsync(ExisKey, "0", 60);

        await RedisHelper.SetAsync(CodeKey, Code, 900);
    }

    /// <summary>
    /// 验证码校验
    /// </summary>
    /// <param name="phone"></param>
    /// <param name="code"></param>
    /// <returns></returns>
    public static async Task Valid(string phone, string code)
    {
        string CodeKey = $"PHONECODE_CODE_{phone}";

        if (!await RedisHelper.ExistsAsync(CodeKey)) throw Oops.Oh("验证码无效");

        string dbcode = await RedisHelper.GetAsync(CodeKey);

        if (dbcode != code) throw Oops.Oh("验证码错误");

    }
}


